<?php

class Model_User extends Model_Entities_User
{
    /*
     * Active account
    */
    public function activeAccount($email, $code) {
        $mapper = $this->getMapper();
        $dbTable = $mapper->getDbTable();
        $data = array('published' => intval(1), 'status' => intval(1), 'active_code' => '');
        $wheres = array('email = ?' => $email, 'active_code = ?' => $code);
        $numRows = $dbTable->update($data, $wheres);
        return $numRows;
    }

    /*
     * Verify account
    */
    public function verifyAccount($email, $code) {
        $mapper = $this->getMapper();
        $dbTable = $mapper->getDbTable();
        $data = array('published' => intval(1), 'status' => intval(2), 'verify_code' => '');
        $wheres = array('email = ?' => $email, 'verify_code = ?' => $code);
        $numRows = $dbTable->update($data, $wheres);
        return $numRows;
    }

    public function getUserInformation($username)
    {
        $array = $this->search('username', $username);
        if (is_array($array) && count($array) > 0) {
            $obj = reset($array);
            $array = $obj->toArray();
        }
        return $array;
    }

    /**
     * Check Admin Login
     */
    public function userLogin($params)
    {
        $email = isset($params['username']) ? $params['username'] : '';
        $password = isset($params['password']) ? $params['password'] : '';
        $password = $this->encryptPassword($password);
        $wheres = array('username = ?' => $email);
        $total = $this->getTotalEntries($wheres);
        if ($total > 0) {
            $list = $this->getArray(0, 0, $wheres);
            if (is_array($list) && count($list) > 0) {
                foreach ($list as $account) {
                    if (isset($account['password']) && $account['password'] == $password) {
                        // update Last Login
                        $usersObj = $this->find($account['id']);
                        $usersObj->save();
                        unset($account['password']);
                        return $account;
                    }
                }
            }
        }
        return false;
    }

    /**
     * Check Front Login
     */
    public function userLoginFont($params)
    {
        $email = isset($params['email']) ? $params['email'] : '';
        $password = isset($params['password']) ? $params['password'] : '';
        $password = $this->encryptPassword($password);
        $wheres = array('email = ?' => $email);
        $total = $this->getTotalEntries($wheres);
        if ($total > 0) {
            $list = $this->getArray(0, 0, $wheres);
            if (is_array($list) && count($list) > 0) {
                foreach ($list as $account) {
                    if (isset($account['password']) && $account['password'] == $password && $account['status'] >= 1) {
                        // update Last Login
                        $usersObj = $this->find($account['id']);
                        $usersObj->save();
                        unset($account['password']);
                        unset($account['active_code']);
                        unset($account['verify_code']);
                        unset($account['reset_passwd_code']);
                        return $account;
                    }
                }
            }
        }
        return false;
    }

    /**
     * Encrypt Password
     */
    public function encryptPassword($string)
    {
        return md5($string);
    }

    /**
     * @todo Check username is exist or not
     * @param string $userName
     * @return bool
     */
    public function checkUserIsExist($userName = '')
    {
        $isExist = false;
        if (!empty($userName)) {
            $rst = $this->getUserInformation($userName);
            if (is_array($rst) && count($rst) > 0 && !empty($rst['username'])) {
                $isExist = true;
            }
        }
        return $isExist;
    }

    /**
     * @todo check email is exist
     * @param unknown_type $email
     * @return string
     */
    public function checkEmailIsExist($email = '')
    {
        $isExist = false;
        if (!empty($email)) {
            $rst = $this->getDataByFieldName('email', $email);
            if (is_array($rst) && count($rst) > 0 && !empty($rst['email'])) {
                $isExist = true;
            }
        }
        return $isExist;
    }

    public function isAdmin($id)
    {
        $result = false;
        $mapper = $this -> getMapper();
        $dbTable = $mapper -> getDbTable();
        $select = $dbTable -> getDefaultAdapter() -> select();
        $select -> from(array('u' => $dbTable -> getTableName()), array('user_id' => 'u.id'));
        $select -> joinInner(array('ru' => $this->getTablePrefix() . 'acl_user'), 'ru.user_id = u.id', array());
        $select -> joinInner(array('r' => $this->getTablePrefix() . 'acl_role'), 'r.id = ru.role_id', array('role_id' => 'r.id', 'role_name' => 'r.role_name'));
        $select -> where('ru.role_id IN (1,2,3)');
        $select -> where('u.id = ?', $id);
        $data = $dbTable -> getDefaultAdapter() -> fetchAll($select);
        if (count($data) > 0) {
            $result = true;
        }

        return $result;
    }

    public  function buildAttributes($params) {
        $attributes = array();
        if(isset($params['id']) && $params['id'] > 0) {
            $attributes['id'] = $params['id'];
            $attributes['modified_date'] = date('Y-m-d H:i:s');
        }
        $attributes['username'] = $params['username'];
        $attributes['password'] = (isset($params['password'])) ? md5($params['password']) : md5($params['username']);
        $attributes['fullname'] = $params['fullname'];
        $name = explode(' ', $params['fullname']);
        $attributes['lastname'] = $name[0];
        $attributes['firstname'] = str_replace($attributes['lastname'], '', $params['fullname']);
        $attributes['email'] = $params['email'];
        $attributes['dob'] = date('Y-m-d H:i:s', mktime(0, 0, 0, $params['mm'], $params['dd'], $params['yyyy']));
        $attributes['gender'] = $params['gender'];
        $attributes['phone'] = (isset($params['phone'])) ? $params['phone'] : '';
        $attributes['address'] = (isset($params['address'])) ? $params['address'] : '';
        $attributes['status'] = (isset($params['status'])) ? $params['status'] : '0';
        $attributes['active_code'] = (isset($params['active_code'])) ? $params['active_code'] : '';
        $attributes['verify_code'] = (isset($params['verify_code'])) ? $params['verify_code'] : '';
        $attributes['image'] = (isset($params['image'])) ? $params['image'] : '';
        if(isset($params['published']) && $params['published'] == 'yes') {
            $attributes['published'] = 1;
        }
        else {
            $attributes['published'] = '0';
        }
        return $attributes;
    }

    public function updatePublished($ids, $value) {
        $mapper = $this->getMapper();
        $dbTable = $mapper->getDbTable();
        $data = array('published' => intval($value));
        if(is_array($ids)) {
            $where = 'id IN ('.implode(', ', $ids).')';
        }
        else if($ids > 0){
            $where = 'id IN ('.$ids.')';
        }
        $numRows = $dbTable->update($data, $where);

        return $numRows;
    }

    /**
     * Enter description here ...
     * @param int $page
     * @param int $limit
     * @param array $wheres
     * @param array $orders
     * @param array $orWheres
     * @param array $likes
     * * @param array $orLikes
     * @return array
     */
    public function getListItems($page = 0, $limit = 0, $wheres = array(), $orders = array('DESC' => 'created_date'), $orWheres = array(), $likes = array(), $orLikes = array()) {
        $mapper = $this->getMapper();
        $dbTable = $mapper->getDbTable();
        $select = $dbTable->getDefaultAdapter()->select();
        $select->from(array('user' => $dbTable->getTableName()));

        if ($limit > 0) {
            $select->limitPage($page, $limit);
        }

        if (is_array($orders) && count($orders) > 0) {
            foreach ($orders as $key => $order) {
                $select->order($order);
            }
        } elseif (is_string($orders) && !empty($orders)) {
            $select->order($orders);
        }

        if (is_array($wheres) && count($wheres) > 0) {
            foreach ($wheres as $key => $where) {
                if (!empty($key) && !intval($key)) {
                    $select->where($key.' = ?', $where);
                }
                else {
                    $select->where($where);
                }
            }
        } elseif (is_string($wheres) && !empty($wheres)) {
            $select->where($wheres);
        }

        if (is_array($orWheres) && count($orWheres) > 0) {
            foreach ($orWheres as $key => $where) {
                if (!empty($key) && !intval($key)) {
                    $select->orWhere($key.' = ?', $where);
                }
            }
        }

        if (is_array($likes) && count($likes) > 0) {
            foreach ($likes as $key => $where) {
                if (!empty($key) && !intval($key)) {
                    $select->where($key.' LIKE ?', $where);
                }
            }
        }

        if (is_array($orLikes) && count($orLikes) > 0) {
            foreach ($orLikes as $key => $where) {
                if (!empty($key) && !intval($key)) {
                    $select->orWhere($key.' LIKE ?', $where);
                }
            }
        }

        //Zend_Debug::dump($select->__toString());die;
        $rst = $dbTable->getDefaultAdapter()->fetchAll($select);
        return $rst;
    }

    /**
     * Enter description here ...
     * @param array $wheres
     * @param array $orWheres
     * @param array $likes
     * @param array $orLikes
     * @return int
     */
    public function getTotal($wheres = array(), $orWheres = array(), $likes = array(), $orLikes = array())
    {
        $mapper = $this->getMapper();
        $dbTable = $mapper->getDbTable();
        $select = $dbTable->getDefaultAdapter()->select();
        $select->from(array('user' => $dbTable->getTableName()), array('CNT' => 'count(DISTINCT user.id)'));

        if (is_array($wheres) && count($wheres) > 0) {
            foreach ($wheres as $key => $where) {
                if (!empty($key) && !intval($key)) {
                    $select->where($key.' = ?', $where);
                }
                else {
                    $select->where($where);
                }
            }
        } elseif (is_string($wheres) && !empty($wheres)) {
            $select->where($wheres);
        }

        if (is_array($orWheres) && count($orWheres) > 0) {
            foreach ($orWheres as $key => $where) {
                if (!empty($key) && !intval($key)) {
                    $select->orWhere($key.' = ?', $where);
                }
            }
        }

        if (is_array($likes) && count($likes) > 0) {
            foreach ($likes as $key => $where) {
                if (!empty($key) && !intval($key)) {
                    $select->where($key.' LIKE ?', $where);
                }
            }
        }

        if (is_array($orLikes) && count($orLikes) > 0) {
            foreach ($orLikes as $key => $where) {
                if (!empty($key) && !intval($key)) {
                    $select->orWhere($key.' LIKE ?', $where);
                }
            }
        }

        $result = $dbTable->getDefaultAdapter()->fetchRow($select);
        return $result['CNT'];
    }

    /******* Global Function - Should not modified ********************************************/

    /**
     * @todo Get info role of the user(Used for Language Resource)
     * @param string $username
     * @return array list role of user
     */
    public function getRoleByUserName($username = '')
    {
        $uList = array();
        if (!empty($username)) {
            $mapper = $this -> getMapper();
            $dbTable = $mapper -> getDbTable();
            $select = $dbTable -> getDefaultAdapter() -> select();
            $select -> from(array('u' => $dbTable -> getTableName()), array('id', 'username'));
            $select -> join(array('a' => $this->getTablePrefix() . 'acl_user'), 'u.id = a.user_id', array('a.id as aid'));
            $arrSelect = array('r.id as rid', 'role_name');
            $select -> join(array('r' => $this->getTablePrefix() . 'acl_role'), 'r.id = a.role_id', $arrSelect);
            $select -> where('u.username = ?', $username);
            $select -> order('u.username ASC');
            // List
            $uList = $this -> getMapper() -> getDbTable() -> getDefaultAdapter() -> fetchAll($select);
        }
        return $uList;
    }

    /**
     * @todo get role user current
     * @return array
     */
    public function getRoleUser($id)
    {
        $mapper = $this -> getMapper();
        $dbTable = $mapper -> getDbTable();
        $select = $dbTable -> getDefaultAdapter() -> select();
        $select -> from(array('u' => $dbTable -> getTableName()), array('id', 'username'));
        $select -> join(array('a' => $this->getTablePrefix() . 'acl_user'), 'u.id = a.user_id');
        $arrSelect = array('role_id' => 'a.role_id', 'role_name' => 'r.role_name');
        $select -> join(array('r' => $this->getTablePrefix() . 'acl_role'), 'a.role_id = r.id', $arrSelect);
        $select -> where('u.id = ?', $id);
        $result = $dbTable -> getDefaultAdapter() -> fetchRow($select);
        return $result;
    }

    //Get user Roles
    public function getUserRoles($uid)
    {
        // Mapper
        $mapper = $this->getMapper();
        $dbTable = $mapper->getDbTable();
        $name = $dbTable->getTableName();
        $select = $dbTable->getDefaultAdapter()->select();
        $selectRoles = $select->from(array('u' => $dbTable->getTableName()), array('u.id as userId'));
        $selectRoles->join(array('a' => $this->getTablePrefix() . 'acl_user'), 'u.id = a.user_id', array('a.role_id as roleId'));
        $selectRoles->join(array('r' => $this->getTablePrefix() . 'acl_role'), 'r.id = a.role_id', array('r.resource_ids as resourceIds'));
        $selectRoles->where('u.id = ?', $uid);
        $tList = $this->getMapper()->getDbTable()->getDefaultAdapter()->fetchAll($selectRoles);
        $resourceIds = $tList[0]['resourceIds'];

        $tblResource = new Model_Entities_AclResource();
        $mapper = $tblResource->getMapper();
        $dbTable = $mapper->getDbTable();
        $name = $dbTable->getTableName();

        $select = $dbTable->getDefaultAdapter()->select();
        $role = $select->from(array('roles' => $dbTable->getTableName()))->where('roles.id IN (' . $resourceIds . ')');
        $listRoles = $tblResource->getMapper()->getDbTable()->getDefaultAdapter()->fetchAll($role);

        $listOrder = array();
        foreach ($listRoles as $role) {
            $listOrder[$role['id']] = $role;
        }

        $resourceIds = explode(',', $resourceIds);
        $listRole = array();
        foreach ($resourceIds as $resource) {
            $listRole[] = $listOrder[$resource];
        }
        return $listRole;
    }
}